﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Channels;
using System.Text;
using System.ServiceModel;
using SMS.MODEL;
using System.Configuration;

namespace SMS.APP 
{
    public class SmsServiceProxy<T> : IDisposable where T : class
    {
        private ChannelFactory<T> channelFactory;
        private T Channel;

        private readonly BasicHttpBinding basicHttpBinding;
        private readonly EndpointAddress endpointAddress;

        private readonly object lockcurrent = new object();
        private bool disposed;

        public SmsServiceProxy()
        {
            if (ConfigurationManager.AppSettings["SmsSeviceUrl"] == null)
            {
                throw new ConfigurationErrorsException("necessary Infomration  is not present in the config file");
            }

            basicHttpBinding = new BasicHttpBinding();
            endpointAddress = new EndpointAddress(ConfigurationManager.AppSettings["SmsSeviceUrl"]);
            disposed = false;
        }

        public T CustomChannel
        {
            get
            {
                if (disposed)
                {
                    throw new ObjectDisposedException(" SmsServiceProxy<" + typeof(T) + "> has been disposed");
                }

                lock (lockcurrent)
                {
                    if (channelFactory == null)
                    {
                        channelFactory = new ChannelFactory<T>(basicHttpBinding, endpointAddress);
                        Channel = channelFactory.CreateChannel();
                   
                    }

                }
                return Channel ;
                
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }


        public void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                    lock (lockcurrent)
                    {
                        if (CustomChannel != null)
                        {
                            ((IClientChannel)CustomChannel).Close();
                        }
                        if (channelFactory != null)
                        {
                            channelFactory.Close();
                        }
                    }

                    Channel = null;
                    channelFactory = null;
                    disposed = true;
                }
            }
        }
         
    }
     
}
